package com.example.LightningController;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Set;

public class Zones extends Activity implements SelectedDevice{
	ArrayList<Zone> zones = new ArrayList<Zone>();
	private Button zoneEditButton;
	private ZonesAdapter adapter;
	private ListView zonesList;
	private int selectedItem = -1;
    private DatabaseManager databaseManager;
    private SPPManager sppInterfaceManager;
    private Item selectedZone;
    private boolean showDevicePicker = false;
    private boolean showDeviceNameEditor = false;

	// private ZoneManager zoneManager;
	private Handler zonesHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
//			Intent zoneControl = new Intent(Zones.this, ZoneControl.class);
//
//			Zones.this.startActivity(zoneControl);
		};
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.zones);

        Log.i("oncreate_database", "Starting application");

        databaseManager = new DatabaseManager(this);

        this.sppInterfaceManager = new SPPManager(this, databaseManager);

		zonesList = (ListView) findViewById(R.id.zones_list);

		zonesList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

                //USE THIS!!!!
//				selectedItem = position;
//
				if (adapter.getMode() == ZonesAdapter.MODES.EDIT_MODE) {
                    selectedZone = null;

                    long ID = Zones.this.databaseManager.GetRecordID(
                            String.valueOf(((Zone) zones.get(position)).getTag()),
                            String.valueOf(((Zone) zones.get(position)).getMacAddress()));
//                    if (Zones.this.databaseManager.removeRecordFromDatabase(String.valueOf(ID)) > 0){
                        for(Item aZone : Zones.this.zones){
                            if (aZone.getID() == ID){
                                selectedZone = aZone;
                                //Zones.this.zones.remove(aZone);
                                //((ZonesAdapter)zonesList.getAdapter()).notifyDataSetChanged();
                            }
                        }
//                    }

                    Intent editZoneIntent = new Intent(Zones.this, EditZone.class);
                    editZoneIntent.putExtra("selected_zone", selectedZone);
                    editZoneIntent.putParcelableArrayListExtra("all_available_zones", Zones.this.zones);
                    startActivityForResult(editZoneIntent, 3);









//                    Toast.makeText(Zones.this, "hello", Toast.LENGTH_SHORT).show();
//					editEvent.putExtra("zone_details", ((ZoneDetails) zones
//							.get(position + 1)).getZoneDetails());

//					Zones.this.startActivity(editEvent);



				} else {
                    Intent openZoneIntent = new Intent(Zones.this, ControllerActivity.class);
                    openZoneIntent.putExtra("selected_zone", ((Zone) zones
							.get(position)));

					Zones.this.startActivity(openZoneIntent);

//					switch (Integer.parseInt(((Zone) zones.get(selectedItem))
//							.getMode())) {
//					case 01:
////						Intent zoneControl = new Intent(Zones.this,
////								ZoneControl.class);
//
//						// zoneControl.putExtra("zone_manager",
//						// Zones.this.currentSession.getCurrentUnit()
//						// .getZBService().getZoneManager());
//
////						Zones.this.startActivity(zoneControl);
//						break;
//					case 10:
////						Utility.showProgressDialog(Zones.this, getResources()
////								.getString(R.string.please_wait));
//
//						break;
//					case 11:
////						Utility.showProgressDialog(Zones.this, getResources()
////								.getString(R.string.please_wait));
//
//						break;
//					}

					// Utility.showProgressDialog(Zones.this, getResources()
					// .getString(R.string.please_wait));
					//
					// SwitchyAttributes switchyAttributes = new
					// SwitchyAttributes();
					//
					// ZONE_ENDPOINT_ON_OFF_ATTRIBUTES[] attributes = new
					// ZONE_ENDPOINT_ON_OFF_ATTRIBUTES[1];
					// attributes[0] = ZONE_ENDPOINT_ON_OFF_ATTRIBUTES.ON_OFF;
					//
					// switchyAttributes.setOnOffAttributes(attributes);
					//
					// Logging.i("gequest", ""+(zones.get(position).getID() -
					// 15));
					// switch (zones.get(position).getID() - 15) {
					// case 0:
					// zone = SWITCHY_ZONES.ZONE_1;
					// break;
					// case 1:
					// zone = SWITCHY_ZONES.ZONE_2;
					// break;
					// case 2:
					// zone = SWITCHY_ZONES.ZONE_3;
					// break;
					// case 3:
					// zone = SWITCHY_ZONES.ZONE_4;
					// break;
					// case 4:
					// zone = SWITCHY_ZONES.ZONE_5;
					// break;
					// case 5:
					// zone = SWITCHY_ZONES.ZONE_6;
					// break;
					// }
					//
					// Zones.this.currentSession
					// .getCurrentUnit()
					// .getZBService(
					// "get-zone-information",
					// Zones.this.currentSession.getUserManager()
					// .getCurrentUser().getUsername(),
					// Zones.this.currentSession.getUserManager()
					// .getCurrentUser().getPassword(),
					// Zones.this.currentSession.getUserManager()
					// .getCurrentUser()
					// .getRememberMeStatus(),
					// zonesHandler)
					// .getCustomHTTPHandler()
					// .getSwitchyCluster(
					// zone,
					// Zones.this.currentSession.getCurrentUnit()
					// .getUnitInfo().getID(),
					// SWITCHY_REQUESTS.SWITCHY_ON_OFF,
					// switchyAttributes);
					//
					// //
					// //////////////////////////////////////////////////////////////////////////////
					// // SwitchyAttributes switchyAttributes1 = new
					// // SwitchyAttributes();
					// //
					// // ZONE_ENDPOINT_SWITCHY_ZONE[] attributes1 = new
					// // ZONE_ENDPOINT_SWITCHY_ZONE[4];
					// // attributes1[0] =
					// // ZONE_ENDPOINT_SWITCHY_ZONE.FOLLOW_MASTER;
					// // attributes1[1] =
					// // ZONE_ENDPOINT_SWITCHY_ZONE.HIGH_TEMP_LEVEL;
					// // attributes1[2] =
					// // ZONE_ENDPOINT_SWITCHY_ZONE.LOW_TEMP_LEVEL;
					// // attributes1[3] = ZONE_ENDPOINT_SWITCHY_ZONE.ZONE_MODE;
					// //
					// // switchyAttributes1.setZoneAttributes(attributes1);
					// //
					// // switch (zones.get(position).getID()) {
					// // case 0:
					// // zone = SWITCHY_ZONES.ZONE_1;
					// // break;
					// // case 1:
					// // zone = SWITCHY_ZONES.ZONE_2;
					// // break;
					// // case 2:
					// // zone = SWITCHY_ZONES.ZONE_3;
					// // break;
					// // case 3:
					// // zone = SWITCHY_ZONES.ZONE_4;
					// // break;
					// // case 4:
					// // zone = SWITCHY_ZONES.ZONE_5;
					// // break;
					// // case 5:
					// // zone = SWITCHY_ZONES.ZONE_6;
					// // break;
					// // }
					// //
					// // Zones.this.currentSession
					// // .getCurrentUnit()
					// // .getZBService(
					// // "get-zone-information",
					// // Zones.this.currentSession.getUserManager()
					// // .getCurrentUser().getUsername(),
					// // Zones.this.currentSession.getUserManager()
					// // .getCurrentUser().getPassword(),
					// // Zones.this.currentSession.getUserManager()
					// // .getCurrentUser()
					// // .getRememberMeStatus(),
					// // zonesHandler)
					// // .getCustomHTTPHandler()
					// // .getSwitchyCluster(
					// // zone,
					// // Zones.this.currentSession.getCurrentUnit()
					// // .getUnitInfo().getID(),
					// // SWITCHY_REQUESTS.SWITCHY_ZONE,
					// // switchyAttributes1);
					//
					// currentSession.getCurrentUnit().getZBService()
					// .addObserver(Zones.this);
				}
			}
		});

		zoneEditButton = (Button) findViewById(R.id.zones_edit_button);

		// temporary
//		generateEntries();
        retrieveEntities();

		adapter = new ZonesAdapter(this, zones, ZonesAdapter.MODES.NON_EDIT_MODE, -1);
		zonesList.setAdapter(adapter);

//		Utility.showNotImplementedAlertDialog(this,
//				"Available rooms information under every zone is static and cannot be changed");
	}

    @Override
    protected void onSaveInstanceState(Bundle icicle) {
        super.onSaveInstanceState(icicle);
              //not used
        icicle.putBoolean("show_device_picker", showDevicePicker);
        icicle.putBoolean("show_device_name_editor", showDeviceNameEditor);
    }

    @Override
    protected void onRestoreInstanceState(Bundle icicle){
       super.onRestoreInstanceState(icicle);
                             //not used
        showDevicePicker = icicle.getBoolean("show_device_picker");
        showDeviceNameEditor = icicle.getBoolean("show_device_name_editor");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("activity_result", requestCode + " | "+resultCode + " | "+data);

        if(requestCode == 2){
        if (resultCode == -1){
            this.addZone(new View(this));
        }
        }

        if (requestCode == 3){
            if(resultCode == RESULT_OK){
                long ID = Zones.this.databaseManager.GetRecordID(((Zone)selectedZone).getTag(),
                ((Zone)selectedZone).getMacAddress());
                    if (Zones.this.databaseManager.removeRecordFromDatabase(String.valueOf(ID)) > 0){
                for(Item aZone : Zones.this.zones){
                    if (aZone.getID() == ID){
                        selectedZone = aZone;
                        Zones.this.zones.remove(aZone);
                        ((ZonesAdapter)zonesList.getAdapter()).notifyDataSetChanged();
                    }
                }
                    }
            }
            if (resultCode == RESULT_CANCELED) {
                Zones.this.retrieveEntities();
                ((ZonesAdapter)Zones.this.zonesList.getAdapter()).notifyDataSetChanged();
            }

            editZones(new View(Zones.this));
        }

        Utility.stopProgressDialog();
    }

	@Override
	protected void onResume() {
		super.onResume();
//		generateEntries();
		if (adapter != null)
			adapter.notifyDataSetChanged();

        if(zones.isEmpty()){
          findViewById(R.id.zones_edit_button).setVisibility(LinearLayout.INVISIBLE);
        }else{
            findViewById(R.id.zones_edit_button).setVisibility(LinearLayout.VISIBLE);
        }
	}

	private void generateEntries() {
//        this.databaseManager.insertIntoDatabase("Zone1", "89:12:12:24");
//        this.databaseManager.insertIntoDatabase("Zone2", "89:12:12:25");
//        this.databaseManager.insertIntoDatabase("Zone3", "89:12:12:26");
//        this.databaseManager.insertIntoDatabase("Zone4", "89:12:12:27");
//        this.databaseManager.insertIntoDatabase("Zone5", "89:12:12:28");
//        this.databaseManager.insertIntoDatabase("Zone6", "89:12:12:29");
//        this.databaseManager.insertIntoDatabase("Zone7", "89:12:12:20");
//
//        this.databaseManager.insertIntoDatabase("Zone8", "89:12:12:21");
//        this.databaseManager.insertIntoDatabase("Zone9", "89:12:12:22");
//        this.databaseManager.insertIntoDatabase("Zone0", "89:12:12:23");
//        this.databaseManager.insertIntoDatabase("Zone11", "89:12:12:23");

//			zones.add(new Zone("Living room", 0, "01", "true",
//                "true", "10",
//                "10", "10", Zone.ButtonState.ON));
////			zones.add(new ZoneDetails(new String[] { "Kitchen", "Dining Room",
////					"Living Room", "Hallway" }, 0));
//        zones.add(new Zone("Neighbours", 1, "01", "true",
//                "true", "10",
//                "10", "10", Zone.ButtonState.ON));
////			zones.add(new ZoneDetails(new String[] { "Bathroom", "Kitchen",
////					"Dining Room", "Living Room", "Hallway" }, 1));
//        zones.add(new Zone("Toilet", 2, "01", "true",
//                "true", "10",
//                "10", "10", Zone.ButtonState.OFF));
////			zones.add(new ZoneDetails(new String[] { "Toilet" }, 2));
//        zones.add(new Zone("Dungeon", 3, "01", "true",
//                "true", "10",
//                "10", "10", Zone.ButtonState.OFF));
////			zones.add(new ZoneDetails(new String[] { "Kitchen", "Dining Room",
////					"Living Room", "Hallway", "Balcony" }, 3));
//        zones.add(new Zone("Cellar", 4, "01", "true",
//                "true", "10",
//                "10", "10", Zone.ButtonState.OFF));
////			zones.add(new ZoneDetails(new String[] { "Kitchen", "Dining Room",
////					"Room Room", "Hallway" }, 4));
//        zones.add(new Zone("Attic", 5, "01", "true",
//                "true", "10",
//                "10", "10", Zone.ButtonState.OFF));
//
//        zones.add(new Zone("Monsters room", 5, "01", "true",
//                "true", "10",
//                "10", "10", Zone.ButtonState.OFF));
//
//        zones.add(new Zone("Monsters room", 6, "01", "true",
//                "true", "10",
//                "10", "10", Zone.ButtonState.OFF));
//
//        zones.add(new Zone("Monsters room", 7, "01", "true",
//                "true", "10",
//                "10", "10", Zone.ButtonState.OFF));
//
//        zones.add(new Zone("Monsters room", 8, "01", "true",
//                "true", "10",
//                "10", "10", Zone.ButtonState.OFF));

//			zones.add(new ZoneDetails(new String[] { "My room", "Kitchen",
//					"Dining Room", "Living Room", "Hallway" }, 5));

		// zoneManager.setZoneItems(zones);
	}

    private void retrieveEntities(){
//        this.zones = this.databaseManager.retrieveZones();
        Log.i("retrieve_entities", ""+this.zones.size());
    }

    public void addZone(View v){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        showDevicePicker = true;

        BluetoothDevice[] selectedBluetoothDevice = new BluetoothDevice[1];

        Set<BluetoothDevice> foundDevices = this.sppInterfaceManager.searchForDevices();
        if (foundDevices != null)
        this.sppInterfaceManager.pickADevice(foundDevices);

        this.sppInterfaceManager.setSelectedDeviceListener(new SelectedDevice() {
            @Override
            public void deviceSelected(BluetoothDevice bluetoothDevice) {

                showDevicePicker = false;
                showDeviceNameEditor = true;

                //To change body of implemented methods use File | Settings | File Templates.
                Log.i("activity_result", "selected");
                if (bluetoothDevice != null){
                    Log.i("activity_result", "device != null");
                    Utility.showProgressDialog(Zones.this, "Connecting to device");
                    sppInterfaceManager.pairDevice(bluetoothDevice, SPPManager.AccessType.ADD_NEW_DEVICE);
                    Utility.stopProgressDialog();
//                    sppInterfaceManager.setOnNewItemListener(new OnNewZoneAdded() {
//                        @Override
//                        public void onNewZoneAdded(long id, String name, String macAddress) {
//                            To change body of implemented methods use File | Settings | File Templates.
//                            Zone newZone = new Zone(Integer.valueOf(String.valueOf(id)), name, macAddress);
//
//                            Zones.this.zones.add(newZone);
//                            ((ZonesAdapter) zonesList.getAdapter()).notifyDataSetChanged();
//
//                            sppInterfaceManager.closeDeviceConnection();
//
//                            Intent openZoneIntent = new Intent(Zones.this, ControllerActivity.class);
//                            openZoneIntent.putExtra("selected_zone", newZone);
//
//                            Zones.this.startActivity(openZoneIntent);
//
//                            not in use
//                            showDevicePicker = false;
//                            showDeviceNameEditor = false;
//
//                            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
//                        }
//                    });
                }
            }
        });

//        if (selectedBluetoothDevice != null)
//            Log.i("activity_result", "finished0");
//        this.sppInterfaceManager.pairDevice(selectedBluetoothDevice[0]);
//        Log.i("activity_result", "finished");
    }

	public void editZones(View v) {
		View v2 = zonesList.getChildAt(0);
		int top = (v2 == null) ? 0 : v2.getTop();
		int visiblePositionOfList = zonesList.getFirstVisiblePosition();

		if (zoneEditButton.getText().equals("Edit")) {
			zoneEditButton
					.setText("Done");

			adapter = new ZonesAdapter(this, zones, ZonesAdapter.MODES.EDIT_MODE, 1);
			zonesList.setAdapter(adapter);

		} else {
			zoneEditButton
					.setText("Edit");
			adapter = new ZonesAdapter(this, zones, ZonesAdapter.MODES.NON_EDIT_MODE, 0);
			zonesList.setAdapter(adapter);
		}

		zonesList.setSelectionFromTop(visiblePositionOfList, top);
	}

    @Override
    public void deviceSelected(BluetoothDevice bluetoothDevice) {
        //To change body of implemented methods use File | Settings | File Templates.
        Log.i("activity_result", "selected");
    }
}
